package com.holis.order.common.filter;

import com.holis.order.common.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class urlLoginFilter  implements Filter {
    @Autowired
    RedisCache redisCache;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("init");
    }

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String requestURI = request.getRequestURI();
        System.out.println(requestURI);
        if (!requestURI.contains("login") && !requestURI.contains("permissionAll")) {
            //验证redis中的uuid是否过期
            String uuid = request.getHeader("uuid");
            //过期重新登录
            if (uuid == null) {
                response.getWriter().write("LoginStatePassed!");
                response.sendRedirect(request.getContextPath() + "/login");
                return;
            }
            Map data = redisCache.getCacheObject(uuid);
            if (data != null ) {
                //刷新uuid
                redisCache.setCacheObject(uuid,data,30, TimeUnit.MINUTES);
                filterChain.doFilter(request, response);
                return;
            }
        } else {
            filterChain.doFilter(servletRequest, servletResponse);
        }
    }
}
